﻿//app.js
import Toast from '/dist/toast/toast';

App({
  globalData: {
    baseUrl: "http://www.jiaertangshi.com:8089/",
    // baseUrl: "http://192.168.0.106:8089/",
    userInfo: {},
    userId: '',
    openId: ''，
    a:1
  },
  getUserInfo: function (cb) {
    var that = this;
    wx.login({
      success: res_login => {
        var code = res_login.code;
        if (res_login.code) {
          wx.getUserInfo({
            success: res_userinfo => {
              var userinfo = res_userinfo.userInfo;
              that.getUserSessionKey(code, userinfo);
              that.globalData.userInfo = res_userinfo.userInfo;
              wx.setStorageSync('userInfo', res_userinfo.userInfo);
            }
          })
        }
      }
    })
  },
  //获取openid session_key userid并保存
  getUserSessionKey: function (code, userinfo) {
    var that = this;
    wx.request({
      url: that.globalData.baseUrl + 'user/wxLogin',
      data: {
        js_code: code, 
        nickName: userinfo.nickName,
        avatarUrl: userinfo.avatarUrl,
        gender: userinfo.gender,
        province: userinfo.province,
        city: userinfo.city,
        country: userinfo.country
      },
      success: res => {
        that.globalData.userId = res.data.userid;
        wx.setStorageSync('userId', res.data.userid);
        that.globalData.openId = res.data.result.openid;
        wx.setStorageSync('openId', res.data.result.openid);
        wx.reLaunch({
          url: '../home/home'
        })
        Toast.success('授权成功');
      },
      fail: res => {
        Toast.fail('授权失败');
      }
    })
  },
  onLaunch: function () {
    var that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          //用户已经授权过从缓存中拿userinfo、openid、userid
          that.globalData.userInfo = wx.getStorageSync('userInfo')
          that.globalData.openId = wx.getStorageSync('openId')
          that.globalData.userId = wx.getStorageSync('userId')
        }
        else{
          that.getUserInfo();
        }
      }
    })
  }
})